
'use strict';

const Service = require('egg').Service;
const schedule = require('node-schedule');
const { Op } = require("sequelize");
const fetch = require("node-fetch");

class TtbPushService extends Service {
    /**
     * 推送列表
     * @param {*} params 
     */
    async list(params){
        const ctx =this.ctx;
        let res = {
            success:false,
            msg:'',
            response_code_enum:null,
        }      
        let push_list ={};
        let where ={};  
        if(!params){
            res.response_code_enum = ctx.app.enums.response_code_enum.miss_required_params;
            return job_group;
        }
        if(params.id && ctx.app.utils.validator.isNum(params.id)){
            where.id =params.id;
        }
        if(params.uuid){
            where.pid =params.pid;
        }
        if(params.name){
            where.name ={
                [Op.like]: `%${params.name}%`
            }
        }
        if(params.title){
            where.title ={
                [Op.like]: `%${params.title}%`
            }
        }
        if(params.schedule){
           where.schedule = params.schedule;
        }
        if(params.modality){
            where.modality =params.modality;
        }
        if(params.target){
            where.target =params.target;
        }
        if(params.next_type){
            where.next_type =params.next_type;
        }
        if(params.status){
            where.status =params.status;
        }
        if(params.schedule_uuid){
            where.schedule_uuid =params.schedule_uuid;
        }
        where.delete_time =null;
        push_list = await this.ctx.model.Push.TtbPush.findAndCountAll({
            attributes: { exclude: ['delete_time']},
            where:where,
            order: [
                ['create_time', 'desc']
            ],
            limit: ctx.limit,
            offset: ctx.offset,
            distinct: true,
            subQuery:false,
        });
        return push_list;
    }

    /**
     * 推送详情
     * @param {*} params 
     */
    async info(params){
        const ctx =this.ctx;
        let res = {
            success:false,
            msg:'',
            response_code_enum:null,
        }      
        let push ={};
        let where ={};  
        if(!params){
            res.response_code_enum = ctx.app.enums.response_code_enum.miss_required_params;
            return job_group;
        }
        if(params.id && ctx.app.utils.validator.isNum(params.id)){
            where.id =params.id;
        }
        if(params.uuid){
            where.uuid =params.uuid;
        }
        if(params.batch_id){
            where.batch_id =params.batch_id;
        }
        if(params.name){
            where.name ={
                [Op.like]: `%${params.name}%`
            }
        }
        if(params.title){
            where.title ={
                [Op.like]: `%${params.title}%`
            }
        }
        if(params.schedule){
           where.schedule = params.schedule;
        }
        if(params.modality){
            where.modality =params.modality;
        }
        if(params.target){
            where.target =params.target;
        }
        if(params.next_type){
            where.next_type =params.next_type;
        }
        if(params.status){
            where.status =params.status;
        }
        if(params.schedule_uuid){
            where.schedule_uuid =params.schedule_uuid;
        }
        where.delete_time =null;
        push = await this.ctx.model.Push.TtbPush.findOne({
            attributes: { exclude: ['delete_time']},
            where:where,
        });
        return push;
    }

    /**
     * 根据推送id处理推送
     * @param {*} params 
     */
    async pushdeal(params){
        const ctx =this.ctx;
        let res = {
            success:false,
            msg:'',
            response_code_enum:null,
        }      
        let push ={};
        let where ={};  
        let send_data ={};
        if(!params){
            res.response_code_enum = ctx.app.enums.response_code_enum.miss_required_params;
            return res;
        }
        if(params.id && ctx.app.utils.validator.isNum(params.id)){
            where.id =params.id;
        }

        push = await this.info({
            id:params.id
        }); 

        if(!push){
            res.msg = '推送不存在';
            return res;
        }
        if(!push.uuid && !push.title && !push.content && !push.platform && !push.modality ){
            res.response_code_enum = ctx.app.enums.response_code_enum.miss_required_params;
            return res;
        }
        switch(push.modality){
            case "once":
            case "period":break;
            default:
                res.msg = '推送形式错误';
                res.response_code_enum = ctx.app.enums.response_code_enum.param_error;
                return res;
        }
        if(push.next_type){
            if(!push.next_type_link){
                res.msg = '推送后续动作链接无效';
                res.response_code_enum = ctx.app.enums.response_code_enum.param_error;
                return res;
            }
        }

        if(push.modality == 'once'){
            // 构建推送发送数据
            send_data.workNo = push.uuid ;
            send_data.pushNotify.title = push.title || '' ;
            send_data.pushNotify.content = push.content ;
            let platform_temp =[];
            let platform =[];
            let ios_test =true;
            platform_temp = push.platform.split(',');
            if(!platform_temp){
                res.msg = '推送目标平台错误';
                res.response_code_enum = ctx.app.enums.response_code_enum.param_error;
                return res;
            }
            for (let item of platform_temp) {
                switch(push.modality){
                    case "android":platform.push(1);break;
                    case "ios_test":platform.push(2);break;
                    case "ios_product":platform.push(2);ios_test =false;break;
                }                
            }
            send_data.pushNotify.plats = platform;
            if(ios_test == true){
                send_data.pushNotify.iosProduction =0;
            }else{
                send_data.pushNotify.iosProduction =1;
            }
            send_data.pushNotify.type = 1;
            if(push.skip_online){
                if(push.skip_online == 'true'){
                    send_data.pushNotify.skipOnline = 1;
                }else{
                    send_data.pushNotify.skipOnline = 0;
                }
            }

            if(push.next_type){
                switch(push.next_type){
                    case 'home':
                        send_data.pushForward.nextType = 0;
                        break;
                    case "link":
                        send_data.pushForward.nextType = 1;
                        send_data.pushForward.url = push.next_type_link;
                        break;
                    default:
                        send_data.pushForward.nextType = 0;
                        break;
                }
            }else{
                send_data.pushForward.nextType = 0;
            }

            if(push.target){
                switch(push.target){
                    case "broadcast":send_data.pushTarget.target =1;break;
                    case "alias":
                        send_data.pushTarget.target =2;
                        let push_alias = push.alias || alias_tag_alias;
                        if(push_alias){
                            res.msg = '推送目标人群错误';
                            res.response_code_enum = ctx.app.enums.response_code_enum.param_error;
                            return res;
                        }
                        let alias =[];
                        try{
                            alias = push_alias.split(',');
                            send_data.pushTarget.alias =alias;
                        }catch(e){
                            res.msg = '推送目标人群错误';
                            res.response_code_enum = ctx.app.enums.response_code_enum.param_error;
                            return res;
                        }    
                        break;
                }                
            }
            if(push.schedule == "true"){
                if(push.schedule_time){
                    let t =0;
                    try{
                        t = ctx.app.utils.time.moment(push.schedule_time).unix();
                        send_data.pushNotify.taskCron =1;
                        send_data.pushNotify.taskTime =t;
                    }catch(e){
                        res.msg = '推送计划时间错误';
                        res.response_code_enum = ctx.app.enums.response_code_enum.param_error;
                        return res;
                    }    
                }
            }    

            // send_data.pushCallback.url =ctx.app.config.push.callback;
            // send_data.pushCallback.params={
            //     type:3
            // };
            // var d = await ctx.app.mobpush.push(send_data);
            await this.push({
                id:push.id
            });
            res.success =true;
            res.data =d;
            return res;
        }
        
        if(push.modality == 'period'){
            if(!push.schedule_time_cron){
                res.msg = '周期推送时间错误';
                res.response_code_enum = ctx.app.enums.response_code_enum.param_error;
                return res;
            }
            if(!ctx.app.enums.api_url.schedule_job_add.value){
                res.msg = '未配置计划任务服务链接';
                res.response_code_enum = ctx.app.enums.response_code_enum.server_error;
                return res;
            }
            let job = {
                name:push.name || push.uuid,
                type:'urllink',
                value:ctx.app.enums.api_url.push.value+`/${push.id}`,
                cron:push.cron
            }
            let response = await fetch(ctx.app.enums.api_url.schedule_job_add.value, {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify(job),
            });
            if(response && response.code ==ctx.app.enums.response_code_enum.success.code){
                if(response.data && response.data.uuid){
                    push.schedule_uuid = response.data.uuid;
                    await push.save();                    
                    res.msg = '成功';
                    return res;
                }
            }                                   
        }

        res.msg = '推送失败';
        res.response_code_enum = ctx.app.enums.response_code_enum.server_error;
        return res;         
    }

    /**
     * 根据推送id进行一次推送
     * @param {*} params 
     */
    async push(params){
        const ctx =this.ctx;
        let res = {
            success:false,
            msg:'',
            response_code_enum:null,
        }      
        let push ={};
        let where ={};  
        let send_data ={};
        if(!params){
            res.response_code_enum = ctx.app.enums.response_code_enum.miss_required_params;
            return res;
        }
        if(params.id && ctx.app.utils.validator.isNum(params.id)){
            where.id =params.id;
        }

        push = await this.info({
            id:params.id
        }); 

        if(!push){
            res.msg = '推送不存在';
            return res;
        }
        if(!push.uuid && !push.title && !push.content && !push.platform && !push.modality ){
            res.response_code_enum = ctx.app.enums.response_code_enum.miss_required_params;
            return res;
        }
        switch(push.modality){
            case "once":
            case "period":break;
            default:
                res.msg = '推送形式错误';
                res.response_code_enum = ctx.app.enums.response_code_enum.param_error;
                return res;
        }
        if(push.next_type){
            if(!push.next_type_link){
                res.msg = '推送后续动作链接无效';
                res.response_code_enum = ctx.app.enums.response_code_enum.param_error;
                return res;
            }
        }

        // 构建推送发送数据
        send_data.workNo = push.uuid ;
        send_data.pushNotify.title = push.title || '' ;
        send_data.pushNotify.content = push.content ;
        let platform_temp =[];
        let platform =[];
        let ios_test =true;
        platform_temp = push.platform.split(',');
        if(!platform_temp){
            res.msg = '推送目标平台错误';
            res.response_code_enum = ctx.app.enums.response_code_enum.param_error;
            return res;
        }
        for (let item of platform_temp) {
            switch(push.modality){
                case "android":platform.push(1);break;
                case "ios_test":platform.push(2);break;
                case "ios_product":platform.push(2);ios_test =false;break;
            }                
        }
        send_data.pushNotify.plats = platform;
        if(ios_test == true){
            send_data.pushNotify.iosProduction =0;
        }else{
            send_data.pushNotify.iosProduction =1;
        }
        send_data.pushNotify.type = 1;
        if(push.skip_online){
            if(push.skip_online == 'true'){
                send_data.pushNotify.skipOnline = 1;
            }else{
                send_data.pushNotify.skipOnline = 0;
            }
        }

        if(push.next_type){
            switch(push.next_type){
                case 'home':
                    send_data.pushForward.nextType = 0;
                    break;
                case "link":
                    send_data.pushForward.nextType = 1;
                    send_data.pushForward.url = push.next_type_link;
                    break;
                default:
                    send_data.pushForward.nextType = 0;
                    break;
            }
        }else{
            send_data.pushForward.nextType = 0;
        }

        if(push.target){
            switch(push.target){
                case "broadcast":send_data.pushTarget.target =1;break;
                case "alias":
                    send_data.pushTarget.target =2;
                    let push_alias = push.alias || alias_tag_alias;
                    if(push_alias){
                        res.msg = '推送目标人群错误';
                        res.response_code_enum = ctx.app.enums.response_code_enum.param_error;
                        return res;
                    }
                    let alias =[];
                    try{
                        alias = push_alias.split(',');
                        send_data.pushTarget.alias =alias;
                    }catch(e){
                        res.msg = '推送目标人群错误';
                        res.response_code_enum = ctx.app.enums.response_code_enum.param_error;
                        return res;
                    }    
                    break;
            }                
        }
        if(push.schedule == "true"){
            if(push.schedule_time){
                let t =0;
                try{
                    t = ctx.app.utils.time.moment(push.schedule_time).unix();
                    send_data.pushNotify.taskCron =1;
                    send_data.pushNotify.taskTime =t;
                }catch(e){
                    res.msg = '推送计划时间错误';
                    res.response_code_enum = ctx.app.enums.response_code_enum.param_error;
                    return res;
                }    
            }
        }    

        // send_data.pushCallback.url =ctx.app.config.push.callback;
        // send_data.pushCallback.params={
        //     type:3
        // };
        var d = await ctx.app.mobpush.push(send_data);
        d = JSON.parse(d);
        let push_log ={};        
        if(d && d.status == 200){
            if(d.res && d.batchId){
                push.batch_id = d.batchId;
                switch(push.modality){
                    case "once":push.status = 'complete';break;
                    case "period":push.status = 'ongoing';break;
                }                           
                await push.save();

                await this.pushDetail({
                    batch_id:push.batch_id
                });
                res.success =true;
                res.data =d;
                return res;
            }
        }else{
            //推送失败
            push_log ={};    
            push_log = {
                push_id:push.id,
                result: d.res || null,
                success: 0,
            }
            await ctx.service.push.ttbPushLog.add(push_log);         
        }
        res.success =false;
        res.data =d;
        return res;
    }

    /**
     * 查询推送结果详情
     */
    async pushDetail(params){
        const ctx =this.ctx;        
        let res = {
            success:false,
            msg:'',
            response_code_enum:null,
        }      
        if(!params){
            res.response_code_enum = ctx.app.enums.response_code_enum.miss_required_params;
            return res;
        }
        if(!params.batch_id ){
            res.response_code_enum = ctx.app.enums.response_code_enum.miss_required_params;
            return res;
        }
        let push = await this.info({
            batch_id:params.batch_id
        });
        if(!push){
            res.msg ='推送不存在';
            res.response_code_enum = ctx.app.enums.response_code_enum.miss_required_params;
            return res;
        }

        let url =ctx.app.enums.mobpush_api_url.prefix.vale+ctx.app.enums.mobpush_api_url.get_by_workid.vale;
        let data = await ctx.app.mobpush.request(url,{
            appkey:ctx.app.mobpush.appkey,
            workId:params.batch_id
        },false);
        data = JSON.parse(data);
        let push_log = {
            push_id:push.id,
            result:(data && data.res) ? JSON.stringify(data.res) : null,
            success: (data && data.status ==200 && data.res) ? 1 :0,
        }
        await ctx.service.push.ttbPushLog.add(push_log);        
        res.data =(data && data.res) ? data.res :null;
        res.success =true;        
        return res;
    }



}

module.exports = TtbPushService;